<script lang="ts" setup>
import type { AiTrainingDatasetMetaApi } from '#/api/ai/dataset/trainingDatasetMeta';

import { useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  downloadJsonFile,
  generateJsonFile,
  getTrainingDatasetMeta,
} from '#/api/ai/dataset/trainingDatasetMeta';
import { $t } from '#/locales';

import { useGenerateJsonFileSchema } from '../data';

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 100,
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: useGenerateJsonFileSchema(),
  showDefaultActions: false,
});
/** 下载训练的json文件 */
async function handleDownloadJsonFile() {
  const formData = await formApi.getValues();
  if (!formData.versionId) {
    message.error('请先选择版本');
    return;
  }
  // 获取当前日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  const data = await downloadJsonFile(
    formData.id,
    formData.versionId,
    formData.versionNum,
    formData.splitType,
  );
  downloadFileFromBlobPart({
    fileName: `${formattedDate}-${formData.splitType}-样本文件.json`,
    source: data,
  });
}
const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = await formApi.getValues();
    try {
      await (data.downloadFlag
        ? handleDownloadJsonFile()
        : generateJsonFile(data.id, data.versionId, '', data.splitType));
      // 关闭并提示
      await modalApi.close();
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    // 加载数据
    let data = modalApi.getData<AiTrainingDatasetMetaApi.TrainingDatasetMeta>();
    if (!data || !data.id) {
      await formApi.setValues(data);
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getTrainingDatasetMeta(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    await formApi.setValues(data);
  },
});
</script>

<template>
  <Modal title="切换数据集版本" class="w-1/3">
    <Form class="mx-4" />
  </Modal>
</template>
